import StorageUtils from '../../app/storage';
import DB from '../../app/db';
import Utils from "../../utils/index";
import { Control } from 'react-keeper';

const {MOCK_WECHAT_OPEN_ID, __LOCAL__} = require(`../../config/${ENV}.json`);

export default (callback, props)=> {
  let userInfo = StorageUtils.getUser();
  if (userInfo && userInfo.hasOwnProperty('openId') && userInfo.openId !== 'xxx') {
    let proprietor = StorageUtils.getStorageItem('proprietor');
    if (proprietor) {
      Control.replace('/home/my', userInfo);
    }
    getProprietor(userInfo, callback);
  } else {

    if (__LOCAL__) {
      DB.WechatAPI.getLocalUser({openId: MOCK_WECHAT_OPEN_ID}).then(
        function (content) {
          StorageUtils.setStorage('user', content);
          getProprietor(content, callback);
        },
        function (error) {
          alert(JSON.stringify(error));
        }
      ).catch(function (reason) {
        alert(reason);
      });
    } else {
      let code = Utils.GetQueryString(window.location.search, 'code');
      if (code) {
        DB.WechatAPI.getUser({code: code}).then(
          function (content) {
            StorageUtils.setStorage('user', content);
            getProprietor(content, callback);
          },
          function (error) {
            alert('缓存失效，请关闭页面重试。');
            // Control.replace('/home/my', null);
          }
        ).catch(function (reason) {
          alert(reason);
        });
      } else {
        alert('请在微信客户端打开。');
      }
    }
  }
}

function getProprietor(content, callback) {
  DB.WechatAPI.getProprietorByOpenId({openId: content.openId}).then(
    function (content) {
      if (content && content.id) {
        StorageUtils.updateUser({proprietorId: content.id});
        StorageUtils.setStorage('proprietor', content);
        Control.replace('/home/my', content);
      } else {
        StorageUtils.updateUser({proprietorId: ''});
        StorageUtils.removeStorageItem('proprietor');
        callback();
      }
    },
    function (error) {
      StorageUtils.updateUser({proprietorId: ''});
      StorageUtils.removeStorageItem('proprietor');
    }
  ).catch(function (reason) {
    Utils.myAlert(reason);
  });
}
